package com.dc.spring.beanlife;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.lang.reflect.Method;
import java.util.Arrays;

@Component
public class MyBeanPostProcessor implements BeanPostProcessor {

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
//        System.out.println("5.BeanPostProcessor.postProcessBeforeInitialization方法：到学校报名啦"+beanName);
        if (bean.getClass().isAnnotationPresent(RestController.class) ||
                bean.getClass().isAnnotationPresent(Controller.class)) {
            System.out.println("Bean with @RestController or @Controller found: " + beanName);
            Class<?> beanClass = bean.getClass();
            // 获取所有声明的方法
            Method[] methods = beanClass.getDeclaredMethods();
            for (Method method : methods) {
                // 检查是否有 @RequestMapping 注解
                if (method.isAnnotationPresent(RequestMapping.class)) {
                    RequestMapping requestMapping = method.getAnnotation(RequestMapping.class);
                    printRequestMappingInfo(method, requestMapping.value(), requestMapping.method());
                }

                // 检查是否有 @GetMapping 注解
                if (method.isAnnotationPresent(GetMapping.class)) {
                    GetMapping getMapping = method.getAnnotation(GetMapping.class);
                    printRequestMappingInfo(method, getMapping.value(), new RequestMethod[] {RequestMethod.GET});
                }

                // 检查是否有 @PostMapping 注解
                if (method.isAnnotationPresent(PostMapping.class)) {
                    PostMapping postMapping = method.getAnnotation(PostMapping.class);
                    printRequestMappingInfo(method, postMapping.value(), new RequestMethod[] {RequestMethod.POST});
                }
            }
        }
        return bean;
    }
    private void printRequestMappingInfo(Method method, String[] paths, RequestMethod[] methods) {
        System.out.println("Method: " + method.getName());
        System.out.println("Paths: " + Arrays.toString(paths));
        System.out.println("HTTP Methods: " + Arrays.toString(methods));
    }
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
//        System.out.println("8.BeanPostProcessor#postProcessAfterInitialization方法：终于毕业，拿到毕业证啦！");
        return bean;
    }
}
